import websocket from '../../utils/websocket';

const app = getApp()

Page({
    data: {
        product: null,
        formatTime: '',
        isFavorite: false
    },

    onLoad(options) {
        const { id } = options
        if (id) {
            this.loadProductDetail(id)
        }

        // 确保WebSocket连接
        if (!websocket.isConnected) {
            websocket.connect();
        }
    },

    async loadProductDetail(id) {
        try {
            const res = await new Promise((resolve, reject) => {
                wx.request({
                    url: `${app.globalData.baseUrl}/api/products/${id}`,
                    method: 'GET',
                    success: resolve,
                    fail: reject
                })
            })

            if (res.data.success) {
                const product = res.data.data.product
                // 处理图片URL
                product.images = product.images.map(img =>
                    img.startsWith('http') ? img : `${app.globalData.baseUrl}${img}`
                )
                // 处理头像URL
                if (product.seller.avatar && !product.seller.avatar.startsWith('http')) {
                    product.seller.avatar = `${app.globalData.baseUrl}${product.seller.avatar}`
                }

                this.setData({
                    product,
                    formatTime: this.formatDate(product.createdAt)
                })
            } else {
                throw new Error(res.data.message || '获取商品详情失败')
            }
        } catch (error) {
            console.error('获取商品详情失败：', error)
            wx.showToast({
                title: '获取商品详情失败',
                icon: 'none'
            })
        }
    },

    // 格式化日期
    formatDate(dateString) {
        const date = new Date(dateString)
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        const hour = date.getHours().toString().padStart(2, '0')
        const minute = date.getMinutes().toString().padStart(2, '0')
        return `${year}-${month}-${day} ${hour}:${minute}`
    },

    // 预览图片
    previewImage(e) {
        const current = e.currentTarget.dataset.url
        wx.previewImage({
            current,
            urls: this.data.product.images
        })
    },

    // 联系卖家
    contactSeller() {
        const { seller } = this.data.product;
        if (!seller || !seller._id) {
            wx.showToast({
                title: '卖家信息不存在',
                icon: 'none'
            });
            return;
        }

        // 检查用户是否登录
        const token = wx.getStorageSync('token');
        if (!token) {
            wx.showToast({
                title: '请先登录',
                icon: 'none',
                success: () => {
                    wx.navigateTo({
                        url: '/pages/login/login'
                    });
                }
            });
            return;
        }

        // 初始化聊天
        websocket.initChat(this.data.product._id).then(() => {
            // 跳转到聊天页面
            wx.navigateTo({
                url: `/pages/chat/chat?productId=${this.data.product._id}&userId=${seller._id}`
            });
        }).catch(error => {
            console.error('发起聊天失败：', error);
            wx.showToast({
                title: '发起聊天失败',
                icon: 'none'
            });
        });
    },

    // 切换收藏状态
    toggleFavorite() {
        this.setData({
            isFavorite: !this.data.isFavorite
        })
        // TODO: 调用收藏/取消收藏接口
    },

    // 分享商品
    shareProduct() {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },

    // 分享给朋友
    onShareAppMessage() {
        const { product } = this.data
        return {
            title: product.title,
            imageUrl: product.images[0],
            path: `/pages/product/product?id=${product._id}`
        }
    },

    // 分享到朋友圈
    onShareTimeline() {
        const { product } = this.data
        return {
            title: product.title,
            imageUrl: product.images[0],
            query: `id=${product._id}`
        }
    },

    // 立即购买
    confirmPurchase() {
        // 检查登录状态
        const token = wx.getStorageSync('token')
        if (!token) {
            wx.showToast({
                title: '请先登录',
                icon: 'none',
                success: () => {
                    setTimeout(() => {
                        wx.navigateTo({
                            url: '/pages/login/login'
                        })
                    }, 1500)
                }
            })
            return
        }

        // 检查商品状态
        if (this.data.product.status !== '在售') {
            wx.showToast({
                title: '该商品已不可购买',
                icon: 'none'
            })
            return
        }

        // 跳转到订单提交页
        wx.navigateTo({
            url: `/pages/order/submit/submit?productId=${this.data.product._id}`
        })
    },

    // 点击举报按钮
    onReportTap() {
        console.log('点击举报按钮'); // 添加调试日志

        // 检查登录状态
        const token = wx.getStorageSync('token')
        if (!token) {
            wx.showToast({
                title: '请先登录',
                icon: 'none',
                success: () => {
                    setTimeout(() => {
                        wx.navigateTo({
                            url: '/pages/login/login'
                        })
                    }, 1500)
                }
            })
            return
        }

        console.log('准备跳转，商品ID:', this.data.product._id); // 添加调试日志

        // 跳转到举报页面
        wx.navigateTo({
            url: `/pages/report/report?productId=${this.data.product._id}`,
            success: () => {
                console.log('跳转成功'); // 添加调试日志
            },
            fail: (err) => {
                console.error('跳转失败:', err); // 添加调试日志
            }
        });
    }
}) 